<?php

namespace WMApi\Service;

use Think\Model;
use WMApi\Model\WmOrderInfoModel;
use SDXApi\Model\PaymentModel;
use WMApi\Model\UsersModel;
use WMApi\Controller\StoreController;
use WMApi\Service\AliyunPushService;

/**
 * 客户端_订单服务类
 * 
 * @author ^2_3^
 *
 */
class OrderService {
    
    /**
     * 保存京东支付交易号
     * @param array $trade_data 京东回调数据;
     * @param string $order_type 订单类型，默认外卖订单;
     * @return boolean
     * 
     * @author ^2_3^
     */
    public function update_jdpay_log( $trade_data=array(), $order_type=PAY_WM_ORDER ) {
        $order_pay_info = $this->get_pay_log($trade_data['out_trade_no'], $order_type);
        
        $data = array();
        $data['transid'] = $trade_data['tradeNum'];
        
        return D('pay_log')->where( array('log_id'=>$order_pay_info['log_id']) )->save($data);
    }
    
    /**
     * 转到余额支付
     * @param string $order_sn 外卖订单编号;
     * 
     * @author ^2_3^
     */
    public function tobalance_pay( $order_sn = '' ) {
        if( empty($order_sn) ) {
            returnApiError('StoreService->tobalance_pay()参数为空;');
        }
        
        $where_oi = array(
            'order_sn' => $order_sn
        );
        $order_info = M('wm_order_info')->where($where_oi)->find();
        
        $store_c = new StoreController();
        $flag = $store_c->balance_pay( $order_info, '', false);
        if( $flag ) {
            
            return true;
        }else {
            return false;
        }
    }
    
    /**
     * 获取订单及支付信息
     *
     * @param string $out_trade_no 订单编号;
     * @param string $order_type 订单类型(PAY_WM_ORDER[外卖订单, 默认]);
     *
     * @author ^2_3^
     */
    public function get_pay_log( $out_trade_no = '', $order_type=PAY_WM_ORDER ) {
        empty($out_trade_no) && returnApiError('StoreService->get_pay_log()缺少参数;');
    
        $where = array(
            "oi.order_sn" => $out_trade_no,
            "pl.order_type" =>$order_type
        );
        $order_pay_info = M('wm_order_info')
            ->alias('oi')
            ->join('sdx_pay_log pl ON pl.order_id = oi.order_id', 'left')
            ->where( $where )
            ->find();
    
        return $order_pay_info;
    }
    
    /**
     * 获取支付同步返回域名
     * @param $host
     * @return string
     */
    public function get_return_host( $host = '' ) {
        if($host=='api.shidexian.com'){
            $return_host = "w.shidexian.com";
        }elseif($host=='apitest.shidexian.com'){
            $return_host = "test.shidexian.com";
        }else{
            $return_host = "w.shidexian.com";
        }
        return $return_host;
    }
    
    /**
     * 检查是否足够支付
     * @param double $order_amount
     * @param int $user_id
     * 
     * @author ^2_3^
     */
    public function check_money($order_amount, $user_id) {
        if( empty($order_amount) || empty($user_id) ) {
            returnApiError('OrderService->check_money()参数错误;');
        }
        
        $userinfo = M('users')
            ->where( array('user_id'=>$user_id) )
            ->find();
        
        // 用户余额
        $amount = $userinfo['user_money'] + $userinfo['credit_line'];
        
        if( $order_amount > $amount ) {
            // 剩余应付金额(混合支付)
            return $order_amount - $amount;
        }
        
        return $order_amount;
    }
    
    /**
     * 修改订单支付状态
     * @param string $out_trade_no 支付订单编号;
     * @param string $pay_status 支付状态(0-未付款 1-已付款 2-已取消);
     * @param string $order_type 订单类型(0-支付订单; 1-充值; 2-外卖订单;);
     * @param unknown $trade_data 支付回调数据;
     * 
     * @author ^2_3^
     */
    public function order_paid( 
        $out_trade_no = '', 
        $pay_status = ORDER_STATUS_PAYED, 
        $order_type = PAY_WM_ORDER, 
        $trade_data = array() ) 
    {
        $result = array();
        
        /// 订单信息及支付信息
        $wm_oi_model = new WmOrderInfoModel();
        $order_pay_info = $wm_oi_model->get_order_pay_log( $out_trade_no );
        
        if( !empty($order_pay_info) && $order_pay_info['is_paid'] == 0 ) {
            
            /// 订单为已支付
            if( $order_pay_info['order_status'] == ORDER_STATUS_PAYED ) {
                $result['pay_success'] = "订单已付款！详情请到用户中心订单详情查看。";
                $result['status'] = true;
                return $result;
            }
            
            /// 开启事务
            $wm_oi_model->startTrans();
            
            /// 更新状态标志
            $flag_pl = false; //pay_log更新标志;
            $flag_oi = false; //wm_order_info更新标志;
            $flag_oa = false; //wm_order_action更新标志;
            $flag_al = false; //account_log更新标志;
            $flag_u = false;  //users更新标志;
            
            /// (1)、更新支付日志(pay_log)[已支付]
            $data_pl['is_paid'] = 1;
            if( !empty($trade_data) && !empty($trade_data['trade_no']) ) {
                $data_pl['transid'] = $trade_data['trade_no']; //第三方支付平台交易流水号;
            }
            $where_pl = array(
                "log_id" => $order_pay_info['log_id'],
                "order_type" => $order_type
            );
            $flag_pl = M("pay_log")->where( $where_pl )->save( $data_pl );
            
            /// (2)、修改订单支付状态(wm_order_info)[已付款]
            $data_oi['order_status'] = ORDER_STATUS_PAYED;
            $data_oi['pay_time'] = gmtime();
            $where_oi = array(
                "order_id" => $order_pay_info['order_id']
            );
            $flag_oi = $wm_oi_model->where($where_oi)->save($data_oi);
            
            /// (3)、插入订单操作记录(wm_order_action)
            $data_oa = array(
                'seller_id' => $order_pay_info['seller_id'],
                'store_id'  => $order_pay_info['store_id'],
                'order_id'  => $order_pay_info['order_id'],
                'order_status'  => ORDER_STATUS_PAYED,
                'seller_status' => SELLER_STATUS_NOGET,
                'tail_end_status' => TAIL_STATUS_NOGET,
                'action_type'   => 1,   //操作类型 1-用户操作 2-后台操作
                'remark'    => '用户支付',
                'created'   => 'system',
                'add_time'  => gmtime()
            );
            $flag_oa = M('wm_order_action')->data( $data_oa )->add();
            
            /// 支付方式
            $payment_model = new PaymentModel();
            $pay_code = $payment_model->get_pay_code( $order_pay_info['pay_id'] );
            
            //-/ 余额支付
            if( $pay_code == 'balance' ) {
                /// (4)、插入账户变动记录(account_log)
                $data_al = array(
                    "user_id" => $order_pay_info['uid'],
                    "user_money" => $order_pay_info['pay_fee'] * (-1),
                    "change_time" => gmtime(),
                    "change_desc" => sprintf('外卖支付订单 %s', $order_pay_info['order_sn']),
                    "change_type" => ACT_WM_ORDER
                );
                $flag_al = M('account_log')->add( $data_al );
                
                /// (5)、更新用户账号金额(users)[减少]
                $where_u = array(
                    "user_id" => $order_pay_info['uid']
                );
                $flag_u = M('users')->where($where_u)->setDec('user_money', $order_pay_info['pay_fee']);
                
                if( $flag_pl && $flag_oi && $flag_oa && $flag_al && $flag_u ) {
                    $wm_oi_model->commit();
                    
                }else {
                    $wm_oi_model->rollback();
                    returnApiError('余额支付失败，稍后重试或联系客服;');
                }
                
                /// (6)、检查用户等级
                $users_model = new UsersModel();
                $flag_ua = $users_model->check_user_rank( $order_pay_info['uid'] );
                
            } //-end/ balance余额支付
            else {
                if( $flag_pl && $flag_oi && $flag_oa ) {
                    $wm_oi_model->commit();
                
                }else {
                    $wm_oi_model->rollback();
                    returnApiError('余额支付失败，稍后重试或联系客服;');
                }
            }
            
            /// 阿里云app推送
            $title = '新订单提醒';
            $body = "您有新订单需要处理({$order_pay_info['order_sn']});";
            $aliyun_push = new AliyunPushService();
            $message_id = $aliyun_push->app_push($order_pay_info['seller_id'], $title, $body);
            
            $result['pay_success'] = '支付成功！';
            $result['status'] = true;
        }
        
        return $result;
    }
    
    /**
     * 修改订单支付方式
     * @param array $order_info 订单信息;
     * @param int $pay_id 支付方式ID;
     * 
     * @author ^2_3^
     */
    public function change_order_pay_type( $order_info, $pay_id ) {
        if( empty($order_info) || empty($pay_id) ) {
            returnApiError('OrderService->change_order_pay_type($order_info, $pay_id)缺少参数');
        }
        
        $flag = false;
        
        if( $pay_id != $order_info['pay_id'] ) {
            /// 检查支付ID
            $where_p = array(
                "pay_id" => $pay_id,
                "enabled" => 1
            );
            $pay_info = M('payment')->where($where_p)->find();
            empty($pay_info) && returnApiError('OrderService->change_order_pay_type($order_info, $pay_id) pay_id参数无效;');
            
            /// 修改订单支付方式
            $where_oi = array(
                "order_id" => $order_info['order_id']
            );
            $data_oi = array(
                "pay_id" => $pay_id
            );
            $flag = M('wm_order_info')->where($where_oi)->save($data_oi);
            
        }
        
        return $flag;
    }
    
    /**
     * 检查用户余额支付密码
     * @param int $userid
     * @param string $password
     * 
     * @author ^2_3^
     */
    public function check_pay_password( $userid = 0, $password = '' ) {
        $flag = false;
        
        /// 参数验证
        if( empty($userid) || empty($password) ) {
//             w_log('api_log', "{$userid} {$password}");
            returnApiError('OrderService->check_pay_password($userid,$password)缺少参数;');
        }
        
        /// 用户信息
        $where_u = array(
            "user_id" => $userid
        );
        $user_info = D('users')->where($where_u)->find();
        empty( $user_info ) && returnApiError('用户ID无效;');
        empty( $user_info['paypwd'] ) && returnApiError('请先设置支付密码;');
        
        /// 检验密码
        if( strtolower( $user_info['paypwd'] ) == strtolower( $password ) ){
            $flag = true;
            
            //-/ 清除错误次数
            M('users')->where($where_u)->save( array('paypwd_wrong'=>0) );

        }else if( $user_info['paypwd_wrong'] >= 3 ) {
            returnApiError('3次错误，请修改密码;');
            
        }else {
            //-/ 累计错误次数
            M('users')->where($where_u)->setInc('paypwd_wrong', 1);
        }
        
        return $flag;
    }
    
}